<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工单API快速诊断工具</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #409eff;
            padding-bottom: 10px;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            background: #f9f9f9;
            border-left: 4px solid #409eff;
            border-radius: 4px;
        }
        button {
            background: #409eff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #66b1ff;
        }
        .result {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .success {
            background: #f0f9ff;
            border: 1px solid #67c23a;
            color: #67c23a;
        }
        .error {
            background: #fef0f0;
            border: 1px solid #f56c6c;
            color: #f56c6c;
        }
        .info {
            background: #f4f4f5;
            border: 1px solid #909399;
            color: #606266;
        }
        .comparison {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 20px;
        }
        .comparison-item {
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 工单API快速诊断工具</h1>
        
        <div class="test-section">
            <h2>1. 检查配置信息</h2>
            <button onclick="checkConfig()">检查配置</button>
            <div id="configResult" class="result"></div>
        </div>

        <div class="test-section">
            <h2>2. 检查认证Token</h2>
            <button onclick="checkToken()">检查Token</button>
            <div id="tokenResult" class="result"></div>
        </div>

        <div class="test-section">
            <h2>3. 测试用户API（对比用）</h2>
            <button onclick="testUsersAPI()">测试用户API</button>
            <div id="usersResult" class="result"></div>
        </div>

        <div class="test-section">
            <h2>4. 测试工单API</h2>
            <button onclick="testTicketsAPI()">测试工单API</button>
            <div id="ticketsResult" class="result"></div>
        </div>

        <div class="test-section">
            <h2>5. 对比分析</h2>
            <button onclick="compareAPIs()">对比用户API和工单API</button>
            <div id="compareResult" class="result"></div>
        </div>

        <div class="test-section">
            <h2>6. 直接测试后端连接</h2>
            <button onclick="testBackendDirect()">直接测试后端</button>
            <div id="backendResult" class="result"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:9090/api';

        function log(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            const className = type === 'success' ? 'success' : type === 'error' ? 'error' : 'info';
            element.className = `result ${className}`;
            element.textContent = message;
        }

        async function checkConfig() {
            log('configResult', '正在检查配置...', 'info');
            try {
                const config = {
                    API_BASE_URL: API_BASE_URL,
                    expectedUsersURL: `${API_BASE_URL}/users`,
                    expectedTicketsURL: `${API_BASE_URL}/tickets`
                };
                log('configResult', `✅ 配置检查完成:\n${JSON.stringify(config, null, 2)}`, 'success');
            } catch (error) {
                log('configResult', `❌ 配置检查失败: ${error.message}`, 'error');
            }
        }

        async function checkToken() {
            log('tokenResult', '正在检查Token...', 'info');
            try {
                const token = localStorage.getItem('token');
                const userInfo = localStorage.getItem('user_info');
                
                let result = `Token存在: ${!!token}\n`;
                if (token) {
                    result += `Token长度: ${token.length}\n`;
                    try {
                        const parts = token.split('.');
                        if (parts.length === 3) {
                            const payload = JSON.parse(atob(parts[1]));
                            result += `Token用户: ${payload.sub || payload.username || 'N/A'}\n`;
                            result += `Token过期时间: ${payload.exp ? new Date(payload.exp * 1000).toLocaleString() : 'N/A'}\n`;
                            result += `Token是否过期: ${payload.exp && payload.exp * 1000 < Date.now() ? '是 ⚠️' : '否 ✅'}\n`;
                        }
                    } catch (e) {
                        result += `Token解析失败: ${e.message}\n`;
                    }
                }
                
                if (userInfo) {
                    try {
                        const user = JSON.parse(userInfo);
                        result += `\n用户信息:\n`;
                        result += `  用户名: ${user.username}\n`;
                        result += `  角色: ${user.role}\n`;
                        result += `  ID: ${user.id}\n`;
                    } catch (e) {
                        result += `用户信息解析失败: ${e.message}\n`;
                    }
                }
                
                log('tokenResult', result, token ? 'success' : 'error');
            } catch (error) {
                log('tokenResult', `❌ Token检查失败: ${error.message}`, 'error');
            }
        }

        async function testUsersAPI() {
            log('usersResult', '正在测试用户API...', 'info');
            try {
                const token = localStorage.getItem('token');
                const url = `${API_BASE_URL}/users?page=0&size=10`;
                
                const startTime = Date.now();
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token ? `Bearer ${token}` : ''
                    }
                });
                const endTime = Date.now();
                
                let result = `请求URL: ${url}\n`;
                result += `HTTP状态: ${response.status} ${response.statusText}\n`;
                result += `响应时间: ${endTime - startTime}ms\n`;
                result += `Content-Type: ${response.headers.get('content-type')}\n\n`;
                
                const data = await response.json();
                result += `响应数据:\n${JSON.stringify(data, null, 2)}\n\n`;
                
                if (data.success) {
                    result += `✅ 用户API测试成功！\n`;
                    if (data.data && data.data.content) {
                        result += `用户数量: ${data.data.content.length}\n`;
                    }
                } else {
                    result += `⚠️ 响应success为false\n`;
                }
                
                log('usersResult', result, response.ok ? 'success' : 'error');
            } catch (error) {
                log('usersResult', `❌ 用户API测试失败:\n${error.message}\n\n可能的原因:\n1. 后端服务未启动\n2. 网络连接问题\n3. CORS跨域问题`, 'error');
            }
        }

        async function testTicketsAPI() {
            log('ticketsResult', '正在测试工单API...', 'info');
            try {
                const token = localStorage.getItem('token');
                const url = `${API_BASE_URL}/tickets?page=0&size=10`;
                
                let result = `请求URL: ${url}\n`;
                result += `Token存在: ${!!token}\n`;
                if (token) {
                    result += `Token长度: ${token.length}\n`;
                }
                result += `\n`;
                
                const startTime = Date.now();
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token ? `Bearer ${token}` : ''
                    }
                });
                const endTime = Date.now();
                
                result += `HTTP状态: ${response.status} ${response.statusText}\n`;
                result += `响应时间: ${endTime - startTime}ms\n`;
                result += `Content-Type: ${response.headers.get('content-type')}\n\n`;
                
                if (!response.ok) {
                    const errorText = await response.text();
                    result += `❌ 请求失败！\n`;
                    result += `错误响应: ${errorText}\n\n`;
                    
                    if (response.status === 401) {
                        result += `💡 问题: 认证失败\n`;
                        result += `💡 解决: 请重新登录\n`;
                    } else if (response.status === 403) {
                        result += `💡 问题: 权限不足\n`;
                        result += `💡 解决: 检查用户角色是否有权限访问工单列表\n`;
                    } else if (response.status === 400) {
                        result += `💡 问题: 请求参数错误\n`;
                        result += `💡 解决: 检查请求参数格式\n`;
                    } else if (response.status === 404) {
                        result += `💡 问题: API路径不存在\n`;
                        result += `💡 解决: 检查后端路由配置\n`;
                    } else if (response.status === 500) {
                        result += `💡 问题: 服务器内部错误\n`;
                        result += `💡 解决: 查看后端日志\n`;
                    }
                    
                    log('ticketsResult', result, 'error');
                    return;
                }
                
                const data = await response.json();
                result += `响应数据:\n${JSON.stringify(data, null, 2)}\n\n`;
                
                if (data.success) {
                    result += `✅ 工单API测试成功！\n`;
                    if (data.data && data.data.content) {
                        result += `工单数量: ${data.data.content.length}\n`;
                        result += `总数: ${data.data.totalElements}\n`;
                    }
                } else {
                    result += `⚠️ 响应success为false\n`;
                    if (data.message) {
                        result += `错误消息: ${data.message}\n`;
                    }
                }
                
                log('ticketsResult', result, 'success');
            } catch (error) {
                let errorMsg = `❌ 工单API测试失败:\n${error.message}\n\n`;
                
                if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
                    errorMsg += `可能的原因:\n`;
                    errorMsg += `1. 后端服务未启动 (检查 http://localhost:9090)\n`;
                    errorMsg += `2. 网络连接问题\n`;
                    errorMsg += `3. CORS跨域问题\n`;
                    errorMsg += `4. 防火墙阻止\n`;
                } else {
                    errorMsg += `错误详情: ${error.stack || error}`;
                }
                
                log('ticketsResult', errorMsg, 'error');
            }
        }

        async function compareAPIs() {
            log('compareResult', '正在对比分析...', 'info');
            
            const token = localStorage.getItem('token');
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            };
            
            let result = '=== API对比分析 ===\n\n';
            
            // 测试用户API
            try {
                const usersResponse = await fetch(`${API_BASE_URL}/users?page=0&size=10`, { headers });
                const usersData = await usersResponse.json();
                result += `用户API:\n`;
                result += `  状态: ${usersResponse.status} ${usersResponse.statusText}\n`;
                result += `  成功: ${usersResponse.ok ? '✅' : '❌'}\n`;
                result += `  响应格式: ${usersData.success ? '标准格式 ✅' : '异常格式 ❌'}\n\n`;
            } catch (error) {
                result += `用户API: ❌ ${error.message}\n\n`;
            }
            
            // 测试工单API
            try {
                const ticketsResponse = await fetch(`${API_BASE_URL}/tickets?page=0&size=10`, { headers });
                const ticketsData = await ticketsResponse.json();
                result += `工单API:\n`;
                result += `  状态: ${ticketsResponse.status} ${ticketsResponse.statusText}\n`;
                result += `  成功: ${ticketsResponse.ok ? '✅' : '❌'}\n`;
                result += `  响应格式: ${ticketsData.success ? '标准格式 ✅' : '异常格式 ❌'}\n\n`;
            } catch (error) {
                result += `工单API: ❌ ${error.message}\n\n`;
            }
            
            result += `=== 分析结果 ===\n`;
            result += `如果用户API成功但工单API失败，可能的原因:\n`;
            result += `1. 工单API路径配置错误\n`;
            result += `2. 工单API需要特殊权限\n`;
            result += `3. 后端工单控制器未正确配置\n`;
            result += `4. 数据库中没有工单数据（这不会导致错误，只是返回空列表）\n`;
            
            log('compareResult', result, 'info');
        }

        async function testBackendDirect() {
            log('backendResult', '正在直接测试后端连接...', 'info');
            
            const tests = [
                { name: '根路径', url: 'http://localhost:9090/' },
                { name: 'API根路径', url: 'http://localhost:9090/api' },
                { name: '健康检查', url: 'http://localhost:9090/actuator/health' },
                { name: '用户API', url: `${API_BASE_URL}/users` },
                { name: '工单API', url: `${API_BASE_URL}/tickets` }
            ];
            
            let result = '=== 后端连接测试 ===\n\n';
            
            for (const test of tests) {
                try {
                    const startTime = Date.now();
                    const response = await fetch(test.url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
                        }
                    });
                    const endTime = Date.now();
                    
                    result += `${test.name} (${test.url}):\n`;
                    result += `  状态: ${response.status} ${response.statusText}\n`;
                    result += `  响应时间: ${endTime - startTime}ms\n`;
                    result += `  结果: ${response.ok ? '✅ 可访问' : '❌ 不可访问'}\n\n`;
                } catch (error) {
                    result += `${test.name} (${test.url}):\n`;
                    result += `  错误: ${error.message}\n`;
                    result += `  结果: ❌ 无法连接\n\n`;
                }
            }
            
            log('backendResult', result, 'info');
        }
    </script>
</body>
</html>

